import axios from 'axios';
import EventBus from '@/utils/event-bus.js';
import SnowflakeId from 'snowflake-id';
import { loginpclog, loginpclog_list } from '@/api/index.js';
import DialogHandle from '@/views/components/dialog.js';
// 创建请求实例
const instance = axios.create({
  baseURL: '/emto',
  // 指定请求超时的毫秒数
  timeout: 100000,
  // 表示跨域请求时是否需要使用凭证
  withCredentials: false,
});

// 前置拦截器（发起请求之前的拦截）
instance.interceptors.request.use(
  (config) => {
    console.log('config:', config);
    /**
     * 在这里一般会携带前台的参数发送给后台，比如下面这段代码：
     * const token = getToken()
     * if (token) {
     *  config.headers.token = token
     * }
     */
    if (config.data) {
      if (localStorage.getItem('userinfo')) {
        if (!config.data.hasOwnProperty('userId')) {
          config.data.userId = JSON.parse(localStorage.getItem('userinfo')).id;
        }
        if (!config.data.hasOwnProperty('token')) {
          config.data.token = JSON.parse(localStorage.getItem('userinfo')).token;
        }
        if (!config.data.hasOwnProperty('adminUseridLogin')) {
          config.data.adminUserid = JSON.parse(localStorage.getItem('userinfo')).adminUseridLogin;
        }
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 后置拦截器（获取到响应时的拦截）
instance.interceptors.response.use(
  (response) => {
    console.log('response:', response);
    /**
     * 根据你的项目实际情况来对 response 和 error 做处理
     * 这里对 response 和 error 不做任何处理，直接返回
     */
    if (response.data.code == '400400') {
      // console.log(response.data.code, response.data.msg);
      // let user = JSON.parse(localStorage.getItem('userinfo'));
      // const snowflake = new SnowflakeId();
      // // localStorage.removeItem('vipinfo');
      // let id = snowflake.generate();
      // loginpclog({ pcCode: id, userId: user.id }).then((res) => {
      //   console.log('res', res);
      //   if (res.data.code == '200') {
      //     loginpclog_list({ pcCode: id }).then((res) => {
      //       console.log('res2:', res);
      //       if (res.data.code === 200 && res.data.data.userinfo) {
      //         userinfo.value = res.data.data.userinfo;
      //         localStorage.setItem('userinfo', JSON.stringify(res.data.data.userinfo));
      //         localStorage.setItem('vipinfo', JSON.stringify(res.data.data.vipinfo));
      //         return axios.request(response.config);
      //       }
      //     });
      //   }
      // });
      const dialog = DialogHandle({
        title: '请登录',
        content: '<div class="text-center">打开微信扫一扫登录系统</div>',
        onConfirm: () => {
          return new Promise(async (resolve) => {
            dialog.showLoading();
            setTimeout(() => {
              dialog.hideLoading();
              resolve();
            }, 1500);
          });
        },
      });
    } else {
      return response;
    }
  },
  (error) => {
    const { response } = error;
    if (response && response.data) {
      return Promise.reject(error);
    }
    const { message } = error;
    console.error(message);
    return Promise.reject(error);
  },
);

// 导出常用函数

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 */
export const post = (url, data = {}, params = {}) => {
  const user = JSON.parse(localStorage.getItem('userinfo'));
  if (user) {
    data.token = user.token;
    data.adminUserid = user.id;
  }
  return instance({
    method: 'post',
    url,
    data,
    params,
  });
};

/**
 * @param {string} url
 * @param {object} params
 */
export const get = (url, params = {}) => {
  return instance({
    method: 'get',
    url,
    params,
  });
};

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 */
export const put = (url, data = {}, params = {}) => {
  const user = JSON.parse(localStorage.getItem('userinfo'));
  if (user) {
    data.token = user.token;
  }

  return instance({
    method: 'put',
    url,
    params,
    data,
  });
};

/**
 * @param {string} url
 * @param {object} params
 */
export const _delete = (url, params = {}) => {
  const user = JSON.parse(localStorage.getItem('userinfo'));
  if (user) {
    data.token = user.token;
  }
  return instance({
    method: 'delete',
    url,
    params,
  });
};

export default instance;

